#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "task.h"

#define N 3

typedef void(*fun_t)();

fun_t tasks[N] = { NULL };

void loadTask()
{
    tasks[0] = PrintLog;
    tasks[1] = Download;
    tasks[2] = MysqlDataSync;
}

void HandlerTask()
{
    int i =0;
    for(i = 0; i < N; ++i)
    {
        tasks[i]();
    }
}

void DoOtherThing()
{
    HandlerTask();
}

void ChildRun()
{
    //int *p = NULL;
    int cnt = 5;
    while(cnt)
    {
        printf("I am child process, pid: %d, ppid:%d, cnt: %d\n", getpid(), getppid(), cnt);
        sleep(1);
        cnt--;
        //*p = 100;
    }
}

int main()
{
    printf("I am father, pid: %d, ppid:%d\n", getpid(), getppid());

    pid_t id = fork();
    if(id == 0)
    {
        // child
        ChildRun();
        printf("child quit ...\n");
        exit(123);
    }

    loadTask();
    // father no block
    while(1)
    {
        int status = 0;
        pid_t rid = waitpid(id, &status, WNOHANG); // no block
        if(rid == 0)
        {
            printf("child is running, father check next time!\n");
            usleep(1000);
            DoOtherThing();
        }
        else if(rid > 0)
        {
            if(WIFEXITED(status))
            {
                printf("child quit success, child exit code : %d\n", WEXITSTATUS(status));
            }
            else
            {
                printf("child quit unnormal\n");
            }
            break;
        }
        else
        {
            printf("waitpid fail!\n");
            break;
        }
    }

    //sleep(6);
    // fahter
    //pid_t rid = wait(NULL);
    // int status = 0;
    // pid_t rid = waitpid(id, &status, 0);
    // if(rid > 0)
    // {
    //     if(WIFEXITED(status))
    //     {
    //         printf("child quit success, child exit code : %d\n", WEXITSTATUS(status));
    //     }
    //     else
    //     {
    //         printf("child quit unnormal\n");
    //     }
    //     printf("wait success, rid: %d\n", rid);
    // }
    // else
    // {
    //     printf("wait failed !\n");
    // }
    // sleep(3);
    // printf("father quit, status: %d, child quit code : %d, child quit signal: %d\n", status, (status>>8)&0xFF, status & 0x7F);

    return 0;
}
